#!/bin/bash
# #######################################################################################
#
# Copyright (c) KylinSoft Co., Ltd. 2024. All rights reserved.
# SecureGuardian is licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# Description: Security Baseline Fix Script for 2.1.2
#
# #######################################################################################

# 功能说明:
# 本脚本用于修复 /etc/passwd 中重复的账号名问题，确保每个账号名唯一。
# 支持 --self-test 参数用于验证修复逻辑。

# 初始化例外账号数组
exceptions=()

# 参数解析函数，支持 --self-test 和 -e 参数
parse_arguments() {
  while [[ $# -gt 0 ]]; do
    case "$1" in
      -e)
        IFS=',' read -r -a custom_exceptions <<< "$2"
        exceptions+=("${custom_exceptions[@]}")
        shift 2
        ;;
      --self-test)
        self_test
        exit $?
        ;;
      *)
        echo "使用方法: $0 [-e 账号名1,账号名2,...] [--self-test]"
        exit 1
        ;;
    esac
  done
}

# 自测功能
self_test() {
  echo "自测模式: 创建两个同名测试用户 testuser，并模拟错误。"

  # 检查并删除已有的测试用户
  if id testuser &>/dev/null; then
    echo "删除已存在的测试用户 testuser..."
    userdel -r testuser
  fi

  # 创建第一个 testuser 用户
  useradd testuser
  echo "已创建第一个 testuser 用户。"

  # 手动添加重复的账号名到 /etc/passwd
  echo "testuser:x:1001:1001::/home/testuser:/bin/bash" >> /etc/passwd
  echo "已在 /etc/passwd 中手动添加重复账号名 testuser，开始修复..."

  # 执行修复
  fix_duplicate_account_names

  # 验证修复结果
  if ! awk -F':' '{print $1}' /etc/passwd | sort | uniq -d | grep -q 'testuser'; then
    echo "自测成功: 账号名重复问题已修复。"
    userdel -r testuser
    return 0
  else
    echo "自测失败: 账号名重复问题未正确修复。"
    return 1
  fi
}

# 修复重复账号名的函数
fix_duplicate_account_names() {
  local duplicate_accounts=$(awk -F':' '{print $1}' /etc/passwd | sort | uniq -d)

  for account in $duplicate_accounts; do
    if [[ " ${exceptions[@]} " =~ " ${account} " ]]; then
      echo "例外账号 $account 被忽略。"
    else
      echo "修复: 删除重复的账号 $account..."
      sed -i "/^${account}:/d" /etc/passwd
      echo "修复成功: 已删除重复的账号 $account。"
    fi
  done
}

# 解析传入的参数
parse_arguments "$@"

# 执行修复任务
echo "正在执行修复..."
if fix_duplicate_account_names; then
  echo "修复完成: 所有账号名已正确设置为唯一。"
  exit 0
else
  echo "修复失败: 部分账号名未能正确修复。"
  exit 1
fi

